import { ConfigEnv, UserConfigExport } from "vite";
import vue from "@vitejs/plugin-vue";
import importToCDN from "vite-plugin-cdn-import";
import { resolve } from "path";
import { visualizer } from "rollup-plugin-visualizer";
import { cdnConfig } from "../cdnConfig";

export default ({ mode }: ConfigEnv): UserConfigExport => {
  return {
    plugins: [
      vue(),
      importToCDN({
        modules: cdnConfig,
      }),
      visualizer({
        filename: 'report.html',
        open: mode === 'report',
        template: 'treemap', // sunburst, treemap, network.
        gzipSize: true,
        brotliSize: true,
      }),
    ],
    server: {
      port: 30000,
      proxy: {
        "/api": {
          target: "http://localhost:3000/",
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
    },
    resolve: {
      alias: {
        "@": resolve(__dirname, "src"),
      },
    },
    build: {
      sourcemap: mode === "development",
      target: "esnext",
      minify: "terser", // 混淆器，terser构建后文件体积更小
      terserOptions: {
        compress: {
          // 生产环境时移除console.log()
          drop_console: true,
          drop_debugger: true,
        },
      },
      rollupOptions: {
        output: {
          manualChunks(id) {
            // node_modules 下文件分包
            if (id.includes("node_modules")) {
              return id
                .toString()
                .split("node_modules/")[1]
                .split("/")[0]
                .toString();
            }
          },
          chunkFileNames: "vendors/[name]-[hash].js", // 三方库文件
          entryFileNames: "js/[name]-[hash].js", // entry js文件
          assetFileNames: "[ext]/[name]-[hash].[ext]", // css文件
        },
      },
    },
  };
};
